﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Net;

namespace Web
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["Type"] != null)
                {
                    string strType = Request.QueryString["Type"].ToString();
                    if (strType == "loginOut")
                    {

                        //更新用户操作记录
                        UpdateUserOperate();
                        HttpContext.Current.Session.Clear();
                    }
                }
                string strSql = "SELECT ID,strName FROM UserGroup WHERE ISEnable=1 AND strName !='系统管理员' order by numSort";
                DataTable dt = SQLHelper.ExecuteDataTable(strSql);
                Fun.SelectOptionAdd(this.ddl_Account, dt, "strName", "ID");
            }
        }

        void UpdateUserOperate()
        {
            try
            {
                string UserID = Session["ID"].ToString();
                //获取该用户的最近一次登录信息记录
                StringBuilder strSqlOperate = new StringBuilder();
                strSqlOperate.Append("  SELECT TOP 1 ID,dt_LoginIn");
                strSqlOperate.Append("  FROM dbo.UserOperate ");
                strSqlOperate.Append("  WHERE UserID=" + UserID);
                strSqlOperate.Append("  ORDER BY dt_LoginIn DESC");
                strSqlOperate.Append("  ");

                DataTable dtOperate = SQLHelper.ExecuteDataTable(strSqlOperate.ToString());

                DateTime dt_LoginIn = Convert.ToDateTime(dtOperate.Rows[0]["dt_LoginIn"]);
                string ID = dtOperate.Rows[0]["ID"].ToString();

                DateTime dt_LoginOut = DateTime.Now;
                TimeSpan ts = dt_LoginOut.Subtract(dt_LoginIn);
                string TimeLength = "";
                TimeLength += ts.Hours.ToString() + "时" + ts.Minutes + "分" + ts.Seconds + "秒";

                StringBuilder strSql = new StringBuilder();
                strSql.Append(" update [UserOperate] set ");
                strSql.Append(" dt_LoginOut='" + dt_LoginOut + "',");
                strSql.Append(" TimeLength='" + TimeLength + "'");
                strSql.Append("  where ID=" + ID);
                SQLHelper.ExecuteNonQuery(strSql.ToString());
            }
            catch
            {

            }

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string strAccountType = ddl_Account.Text;
            if (txtLoginName.Text.Trim() == "")
            {

                string StrScript;
                StrScript = ("<script language=javascript>");
                StrScript += ("alert('请输入账户名!');");
                StrScript += ("</script>");
                System.Web.HttpContext.Current.Response.Write(StrScript);
                return;
            }
            if (txtPassword.Text.Trim() == "")
            {
                string StrScript;
                StrScript = ("<script language=javascript>");
                StrScript += ("alert('请输入密码!');");
                StrScript += ("</script>");
                System.Web.HttpContext.Current.Response.Write(StrScript);
                return;
            }
            //检验账户正确性
            StringBuilder strAccount = new StringBuilder();
            strAccount.Append(" SELECT ID, WB_ID,UserGroup_ID,strLoginName,strRealName,strPassword,ISEnable from Users");
            strAccount.Append(" WHERE  UserGroup_ID=@UserGroup_ID AND LOWER(strLoginName)=@strLoginName ");
            SqlParameter[] para = new SqlParameter[]{
            new SqlParameter("@UserGroup_ID",this.ddl_Account.SelectedValue),
            new SqlParameter("@strLoginName",this.txtLoginName.Text.Trim().ToLower())
            };
            DataTable dtAccount = SQLHelper.ExecuteDataTable(strAccount.ToString(), para);
            if (dtAccount != null && dtAccount.Rows.Count != 0)
            {
                string UserGroup_ID = dtAccount.Rows[0]["UserGroup_ID"].ToString();
                string UserGroupName = SQLHelper.ExecuteScalar("  SELECT strName FROM dbo.UserGroup WHERE ID="+UserGroup_ID).ToString();

                bool ErrorLoginCheck = false;//是否启用了秘密错误检验 
                if (UserGroupName == "营业员")
                {
                    if (Convert.ToBoolean(common.GetWBAuthority()["ErrorLogin_User"]) == true) {
                        ErrorLoginCheck = true;
                    }
                }
                else
                {
                    if (Convert.ToBoolean(common.GetWBAuthority()["ErrorLogin_Admin"]) == true)
                    {
                        ErrorLoginCheck = true;
                    }
                }

                string UserID = dtAccount.Rows[0]["ID"].ToString();

                object objErrorTime=null;
                if (ErrorLoginCheck)
                {
                     objErrorTime = SQLHelper.ExecuteScalar(" SELECT TOP 1 ErrorTime FROM dbo.UserOperate WHERE UserID=" + UserID + " ORDER BY dt_LoginIn desc");
                    if (objErrorTime != null && objErrorTime.ToString() != "")
                    {
                        if (Convert.ToInt32(objErrorTime) >= 3)
                        {
                            DateTime dt_LoginIn = Convert.ToDateTime(SQLHelper.ExecuteScalar(" SELECT TOP 1 dt_LoginIn FROM dbo.UserOperate WHERE UserID=" + UserID + " ORDER BY dt_LoginIn desc"));
                            TimeSpan tsLogin = DateTime.Now.Subtract(dt_LoginIn);
                            if (tsLogin.TotalHours < 24)
                            {
                                Fun.Alert("您的密码已经连续三次输入错误，请于24小时后重试，或请求管理员解除限制！");
                                return;
                            }
                        }
                    }
                }
                string strPassword = dtAccount.Rows[0]["strPassword"].ToString();
                bool ISEnable = Convert.ToBoolean(dtAccount.Rows[0]["ISEnable"]);
                if (Fun.GetMD5_32(txtPassword.Text.Trim()) == strPassword)
                {
                    if (ISEnable)
                    {

                        HttpContext.Current.Session.Clear();
                        Session["WB_ID"] = dtAccount.Rows[0]["WB_ID"].ToString();//该用户所在的网点ID
                       Session["UserGroup_ID"] = UserGroup_ID;
                       Session["UserGroup_Name"] = UserGroupName;
                        Session["ID"] = dtAccount.Rows[0]["ID"].ToString();//用户ID
                        

                        Session["strLoginName"] = dtAccount.Rows[0]["strLoginName"].ToString();//用户登录名
                        Session["strRealName"] = dtAccount.Rows[0]["strRealName"].ToString();
                        //设置保存session的Cookies值
                        Request.Cookies.Clear();
                        Response.Cookies.Clear();
                       
                        HttpCookie cookie = new HttpCookie("LoginInfo");
                        DateTime dtNow = DateTime.Now;
                        TimeSpan ts = new TimeSpan(1, 0, 0, 0);//设置cookie的保存时间为一天
                        cookie.Expires = dtNow.Add(ts);
                        cookie.Values.Add("ID", dtAccount.Rows[0]["ID"].ToString());
                        HttpContext.Current.Response.Cookies.Add(cookie);

                        //添加营业员访问记录
                        AddUserOperate(false,dtAccount);

                        switch (this.ddl_Account.SelectedItem.Text)
                        {
                            case "营业员": Response.Redirect(@"/FrmSetting/user_index.htm"); break;
                            // case "网点管理员": Response.Redirect(@"~/Account/SysWebSiteIndex.aspx"); break;
                            case "单位管理员": Response.Redirect(@"/FrmSetting/index.htm"); break;
                            case "网点管理员": Response.Redirect(@"/FrmSetting/index.htm"); break;
                            case "系统管理员": Response.Redirect(@"~/Account_System/SystemIndex.aspx"); break;
                        }

                    }
                    else
                    {
                        Fun.Alert("当前账户已被禁用，请与管理员联系!");
                        return;

                    }
                }
                else
                {
                    AddUserOperate(true, dtAccount);

                    if (ErrorLoginCheck)
                    {
                        int numErrorTime = 0;
                        if (objErrorTime != null && objErrorTime.ToString() != "")
                        {
                            numErrorTime = Convert.ToInt32(objErrorTime) + 1;
                        }
                        Fun.Alert("这是您第" + numErrorTime + "次输入密码错误，连续输入错误3次以上您的账号将被禁用24小时！");
                        return;
                    }
                    else {
                        Fun.Alert("您输入的密码不正确");
                        return;
                    }

                }
            }
            else
            {
                Fun.Alert("不存在的账户名!");
                return;

            }
        }

      

        private static void AddUserOperate(bool ISError, DataTable dt)
        {
            string IpAddress = "192.168.1.1";
            string hostname = Dns.GetHostName();//得到主机名
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostname);

            foreach (IPAddress ip in addressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    IpAddress = ip.ToString();//暂时获取内容的IPV4地址
                }
            }


            object WBID = dt.Rows[0]["WB_ID"];
            object UserID = dt.Rows[0]["ID"];
            int ErrorTime = 0;
            if (ISError) {//这一次是错误的登陆 
                object objError = SQLHelper.ExecuteScalar(" SELECT TOP 1 ErrorTime FROM dbo.UserOperate where UserID="+UserID+" ORDER BY dt_LoginIn desc");
                if (objError == null || objError.ToString() == "")
                {
                    ErrorTime = 1;
                }
                else {
                    ErrorTime = Convert.ToInt32(objError) + 1;
                }
            }

            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into [UserOperate] (");
            strSql.Append("WBID,UserID,dt_LoginIn,dt_LoginOut,IpAddress,TimeLength,ErrorTime)");
            strSql.Append(" values (");
            strSql.Append("@WBID,@UserID,@dt_LoginIn,@dt_LoginOut,@IpAddress,@TimeLength,@ErrorTime)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@WBID", SqlDbType.Int,4),
					new SqlParameter("@UserID", SqlDbType.Int,4),
					new SqlParameter("@dt_LoginIn", SqlDbType.DateTime),
					new SqlParameter("@dt_LoginOut", SqlDbType.DateTime),
					new SqlParameter("@IpAddress", SqlDbType.NVarChar,50),
					new SqlParameter("@TimeLength", SqlDbType.NVarChar,50),
                    new SqlParameter("@ErrorTime", SqlDbType.Int,4)};
            parameters[0].Value = WBID;
            parameters[1].Value = UserID;
            parameters[2].Value = DateTime.Now;
            parameters[3].Value = DateTime.Now;
            parameters[4].Value = IpAddress;
            parameters[5].Value = "0时0分0秒";
              parameters[6].Value =ErrorTime;
            SQLHelper.ExecuteNonQuery(strSql.ToString(), parameters);

        }
    }
}